package io.github.uicdb.badskill.network;

import io.github.uicdb.badskill.PlayerSkillCapability;
import io.github.uicdb.badskill.PlayerSkillCapabilityProvider;
import io.github.uicdb.badskill.SkillOptionManager;
import io.github.uicdb.badskill.clent.impl.AttributeScreen;
import io.github.uicdb.badskill.clent.impl.VecScTextView;
import io.github.uicdb.badskill.mixin.AttributeMapAccessor;
import io.github.uicdb.badskill.mixin.AttributeSupplierAccessor;
import lombok.RequiredArgsConstructor;
import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.DefaultAttributes;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.registries.ForgeRegistries;

import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;

@RequiredArgsConstructor
public class AtttributeValueSyncPackage {
    private final Map<Attribute,Double> syncMap;


    private static AtttributeValueSyncPackage create(ServerPlayer player){
        var map=  ((AttributeSupplierAccessor)(DefaultAttributes.getSupplier(EntityType.PLAYER)))
                .getInstances().keySet()
                .stream()
                .collect(Collectors.toMap(attribute -> attribute, player::getAttributeValue));
        return new AtttributeValueSyncPackage(map);
    }
    public  void toBytes(FriendlyByteBuf buf) {
       buf.writeMap(syncMap, (buf1, attribute) -> buf1.writeRegistryIdUnsafe(ForgeRegistries.ATTRIBUTES, attribute), FriendlyByteBuf::writeDouble);
    }

    public static AtttributeValueSyncPackage create(FriendlyByteBuf buf) {
        return new AtttributeValueSyncPackage(buf.readMap(buf1 -> buf1.readRegistryIdUnsafe(ForgeRegistries.ATTRIBUTES), FriendlyByteBuf::readDouble));
    }

    public  void handle(Supplier<NetworkEvent.Context> contextSupplier) {
        var context=contextSupplier.get();
        context.enqueueWork(() -> {
            if(context.getDirection().getReceptionSide()== LogicalSide.CLIENT){
                AttributeScreen.SYNC_MAP.clear();
                AttributeScreen.SYNC_MAP.putAll(syncMap);
            }});
        context.setPacketHandled(true);
    }
    public static void sendToClient(ServerPlayer serverPlayer){
        NetWorking.simpleChannel.send(PacketDistributor.PLAYER.with(()->serverPlayer),AtttributeValueSyncPackage.create(serverPlayer) );
    }
}
